<template>
    <div class="container">
        <h3>添加员工</h3>
        <el-form :model="ruleForm" ref="ruleForm" :rules="rules" :label-position="labelPosition" label-width="100px" class="demo-ruleForm">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="姓名：" prop="name">
                       <el-input placeholder="请输入内容" v-model="ruleForm.name" style="width:300px">
                        </el-input>
                    </el-form-item>

                    <el-form-item label="头像：">
                        <el-upload
                            class="upload-poster"
                                action="https://jsonplaceholder.typicode.com/posts/"
                                :show-file-list="false"
                                :on-change="imgPreview"
                                :auto-upload="false">
                                <img v-if="headImg" :src="headImg" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                        jpg、png、gif格式，60x60像素，不超过2MB
                    </el-form-item>
                </el-col>
                <el-col :span="10">
                    <el-form-item label="手机号：" prop="phone">
                       <el-input placeholder="请输入内容" v-model="ruleForm.phone" style="width:300px">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="部门：" prop="departmentId">
                        <el-cascader
                            style="width:300px;"
                            v-model="ruleForm.departmentId"
                            @change="ele"
                            :options="options"
                            :props="{
                                checkStrictly: true,
                                label:'name',
                                value:'id',
                                children:'children'
                             }"
                            clearable>
                        </el-cascader>
                    </el-form-item>
                    <el-form-item label="身份证号码：">
                       <el-input placeholder="请输入内容" v-model="ruleForm.idCard" style="width:300px">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="学历：">
                        <el-select v-model="ruleForm.education"  style="width:300px !important">
                            <el-option v-for="item in education" :key="item.id" :label="item.name" :value="item.name">{{item.name}}</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="入职时间：" prop="jobtime">
                        <el-date-picker
                            style="width:300px"
                            v-model="ruleForm.jobtime"
                            value-format="yyyy/MM/dd"
                            type="date"
                            placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>

                </el-col>
            </el-row>
            <el-row>
                <el-form-item label-width="0px">
                    <el-checkbox v-model="checked">开通账号</el-checkbox>
                    <span style="margin-left:20px;font-size:12px;">用户名为手机号码</span>
                </el-form-item>
                <el-col :span="12">
                    <el-form-item label="密码：">
                       <el-input placeholder="******" v-model="password" style="width:300px">
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="10">
                    <el-form-item label="重复密码：">
                       <el-input placeholder="******" v-model="repeatpass" style="width:300px">
                        </el-input>
                    </el-form-item>

                </el-col>

            </el-row>
            <el-form-item class="footerFixed" label-width="0px">
                <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                <el-button @click="backPage">返回</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
    import {staff,company_findById,staff_findById,staff_save,staff_delete,staff_getId,staffuser_save,staffuser_findById,staffuser_update,staffuser_findByAll} from '@/request/api'
    export default {
        data() {
            return {
				password:'',
                repeatpass:'',
                checked:true,
                education:[
                    {name:'文盲'},
                    {name:'小学'},
                    {name:'初中'},
                    {name:'高中'},
                    {name:'大专'},
                    {name:'本科'},
                    {name:'硕士'},
                    {name:'博士'},
                ],
                headImg:'',
                options:[],
                // password:'',
                id:'',
                label:'',
                labelPosition:'right',
                allMessage: '',
                ruleForm: {
                    userType:"COMMON",
                    file:'',
                    password:''
                    // state:'启用'
                },
				files:'',
                idList:[],
                rules:{
                   password: [
                        { required: true, message: '不能为空', trigger: 'change' }
                    ],
                    name: [
                        { required: true, message: '不能为空', trigger: 'change' }
                    ],
                    departmentId: [
                        { required: true, message: '不能为空', trigger: 'change' }
                    ],
                    phone: [
                        { required: true, message: '不能为空', trigger: 'change' }
                    ],
                },
            };
        },
        mounted(){
            this.id = this.$route.query.id
            this.sid = this.$route.query.sid
            // console.log(this.sid)
            this.init1()
            if(this.id == undefined){

            }else{
                this.init()
            }
        },
        methods: {
            changeType(ele){
                console.log(ele)
            },
            imgPreview(file,fileList) {
                this.headImg =  URL.createObjectURL(file.raw);
                let fileName = file.name;
                let regex = /(.jpg|.gif|.png|.jpeg)$/;
                if (regex.test(fileName.toLowerCase())){
                    this.files = file.raw
                    this.ruleForm.headImg = file.name
                } else {
                    this.$message.error('请选择正确格式的图片');
                }

            },
            init1(){
                var id = localStorage.getItem("companyId")
                company_findById(id).then((res)=>{
                    this.options.push({id:res.data.id,name:res.data.abbreviation,children:[]})
                    staffuser_findByAll("").then((res)=>{
                        this.options[0].children = res.data
                    })
                })
            },
            init(){
                var id = localStorage.getItem("companyId")
                staffuser_findById(this.id).then((res)=>{
                    this.ruleForm = res.data
                    if(this.ruleForm.departmentId == null || this.ruleForm.departmentId == "" || this.ruleForm.departmentId == "null"){
                        this.idList.push(id)
                    }else{
                        this.idList.push(id)
                        var arr = this.ruleForm.departmentId.split(",")
                            for (let i = 0; i < arr.length; i++) {
                            this.idList.push(arr[i])

                        }
                    }
                    this.ruleForm.departmentId = this.idList
                    this.ruleForm.oldHeadImg = res.data.headImg
                    if(this.ruleForm.headImg == "" || this.ruleForm.headImg == 'null' || this.ruleForm.headImg == null){
                        this.ruleForm.headImg = this.ruleForm.headImg
                    }else{
                        this.headImg = this.$store.state.plantImg + this.ruleForm.headImg
                    }
                })
            },
            ele(ele){

            },
            handleChange(value) {

            },
            backPage () {
                this.$router.go(-1);

            },
            submitForm(formName) {
                // console.log(this.ruleForm.departmentId)
                 this.$refs[formName].validate((valid) => {
                    if (valid) {
                        var arr = ""
                        for (let i = 0; i < this.ruleForm.departmentId.length; i++) {
                            arr = this.ruleForm.departmentId[i]
                        }
                        this.ruleForm.departmentId = arr

                        this.ruleForm.username = this.ruleForm.phone
						if(this.id == undefined){
							if(this.checked == true){

								if(this.repeatpass == "" && this.password == ""){
									this.$notify({
										title: '提示',
										message: '密码或重复密码不能为空',
										type: 'info'
									});
									return false

								}else{

									if(this.repeatpass != this.password){
										this.$notify({
											title: '提示',
											message: '密码和重复密码填写不一致',
											type: 'info'
										});
										return false
									}

								}
							}
						}else{
							if(this.repeatpass != this.password){
								this.$notify({
									title: '提示',
									message: '密码和重复密码填写不一致',
									type: 'info'
								});
								return false
								// console.log(333)
							}
						}
                       // coinsole.log(444)
                        if(this.ruleForm.phone == "" || this.ruleForm.idCard == undefined){

                        }else{
                            let reg = /^1[34578]\d{9}$/;
                            if(!reg.test(this.ruleForm.phone)){
                                this.$notify({
                                    title: '提示',
                                    message: '手机号格式不正确，请重新填写',
                                    type: 'info'
                                });
                                return false
                            }
                        }
                      if(this.password != ""){
                        this.ruleForm.password = this.password
                      }else{
                        this.ruleForm.password = this.ruleForm.password
                      }
                        // if(this.ruleForm.idCard == "" || this.ruleForm.idCard == undefined){

                        // }else{
                        //     let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
                        //     if(!reg.test(this.ruleForm.idCard)){
                        //         this.$notify({
                        //             title: '提示',
                        //             message: '身份证号输入有误，请重新填写',
                        //             type: 'info'
                        //         });
                        //         return false
                        //     }
                        // }
                        if(this.ruleForm.state == "启用"){
                            this.ruleForm.state = "0"
                        }
                        if(this.ruleForm.state == "禁用"){
                            this.ruleForm.state = "1"
                        }
                      let data = JSON.parse(JSON.stringify(this.ruleForm))
                      if(data.jobtime){
                        data.jobtime = new Date(data.jobtime)
                      }
						            this.ruleForm = data
                        let formdata = new FormData()
						          formdata.append("files",this.files)
                        for(var a in this.ruleForm){
                            if(this.ruleForm[a] == null || this.ruleForm[a] == "null"){
                                this.ruleForm[a] = ""
                                formdata.append(a,'')
                            }else{
                                formdata.append(a,this.ruleForm[a])
                            }
                        }
                        if(this.id == undefined){
                             staffuser_save(formdata).then((res)=>{
                                this.$notify({
                                    title: '提示',
                                    message: '保存成功',
                                    type: 'success'
                                });
                                this.$router.go(-1)
                            })
                        }else{
                            staffuser_update(formdata).then((res)=>{
                                this.$notify({
                                    title: '提示',
                                    message: '修改成功',
                                    type: 'success'
                                });
                                this.$router.go(-1)
                            })
                        }
                    }else{
                        return false
                    }
                 })
            }
        }
    }
</script>

<style scoped lang="less">
.demo-ruleForm{
    margin-top: 10px;
}
.demo-ruleForm .el-radio--small.is-bordered{
    width: 120px !important;
    margin-right: 10px !important;
}
.box{
    width: 85%;
    margin-bottom: 15px;
    dl{
        margin-bottom: 20px;
        overflow: hidden;
        dt{ margin-bottom: 5px; font-size: 14px;}
        dd{ font-weight: 500; font-size: 12px; float: left; width: 50%; line-height: 24px;}
    }
    dl:last-child{
        margin-bottom: 0;
    }
    .el-col-11{
        height: 200px;
        overflow-y: auto;
        margin-left: 10px;
        border-left: 1px solid #EBEEF5;
        padding-left: 10px;
        p{ color: #303133;}
        .record-tip-con{
            padding-top: 10px;
        }
    }
}
.demo-ruleForm{
    margin-top: 20px;
}
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    width:180px;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
